﻿using System;
using System.Threading;
using System.IO;
using System.Threading.Tasks;
/*
* Class that sends PING to irc server every 15 seconds
*/
namespace IRCTest{
    class PingSender : IDisposable
    {
        static StreamReader test;
        static string PING = "PONG ";
        static string Return = null;
        private Thread pingSender;
        private bool run = true;
        // Empty constructor makes instance of Thread
        public PingSender(StreamReader link)
        {
            test = link;
            pingSender = new Thread(new ThreadStart(this.Run));
        }
        // Starts the thread
        public void Start()
        {
            pingSender.Start();
        }
        public void setResponse(String Response)
        {
            Return = Response;
        }
        // Send PING to irc server every 15 seconds
        public void Run()
        {
            while (run)
            {

                    try
                    {
                        if (IRCBot.writer == null)
                            break;
                        IRCBot.writer.WriteLine(PING + Return);
                    }
                        

                    finally
                    {
                        IRCBot.writer.Flush();
                        Thread.Sleep(1000);
                    }
            }
        }

        public void Dispose()
        {
            Task Abort = new Task(new Action(() => pingSender.Abort()));
            try
            {
                Task.Factory.StartNew(new Action(() => run = false)).ContinueWith(x => Abort).Wait();

            }
            finally
            {
                Return = null;
                pingSender = null;
            }
        }
    }
}